package top.leyi.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import top.leyi.dao.TalkCache;
import top.leyi.entity.ObjRedisTemplate;
import top.leyi.entity.Talk.SimpleTalk;
import top.leyi.entity.Talk.Talk;
import top.leyi.entity.Visit;
import top.leyi.entity.user.User;
import top.leyi.mapper.TalkMapper;
import top.leyi.mapper.VisitMapper;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

@Service
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    StringRedisTemplate  redisTemplate;

    @Autowired
    ObjRedisTemplate objRedisTemplate;
    @Autowired
    VisitMapper mapper;
    @Autowired
    TalkMapper talkMapper;

    private final long TALK_SCHE = 10;

    Date date = new Date();
    Calendar cal = Calendar.getInstance();
    {
        cal.setTime(date);//date 换成已经已知的Date对象
        cal.add(Calendar.HOUR_OF_DAY, +1);// before 8 hour
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
    }
    long initDelay = cal.getTimeInMillis() - System.currentTimeMillis();


    /**
     * 开启定时存储访问人数的功能
     * @param contextRefreshedEvent
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if(redisTemplate == null){
            return;
        }
        redisTemplate.opsForValue().setIfAbsent("visitors", "0");
        System.out.println("监听使用人数程序已开始");

        visitLog();

        System.out.println("开启热门说说缓存");
         //TODO
        dotalkCache();
    }





    public  void visitLog() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        int period = 1000*60*60;
        executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                int visitors =  Integer.parseInt(redisTemplate.opsForValue().get("visitors"));
                Calendar cal = Calendar.getInstance();
                int day = cal.get(Calendar.DATE);
                int month = cal.get(Calendar.MONTH) + 1;
                int year = cal.get(Calendar.YEAR);
                int hour = cal.get(Calendar.HOUR);

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Visit visit = new Visit();
                visit.setDayTime(format.format(cal.getTime()));
                visit.setHourTime(hour );
                visit.setVisitors(visitors);

                mapper.addVisitor(visit);

                redisTemplate.opsForValue().set("visitors", "0");
                System.out.println("添加成功");
            }
        }, initDelay, period, TimeUnit.MILLISECONDS);

    }


       public  void dotalkCache() {

           ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

           List<SimpleTalk> result = talkMapper.queryHotTalks();
           redisTemplate.opsForZSet().removeRange("hotTalk", 0, -1);

           executor.scheduleAtFixedRate(new Runnable() {
               @Override
               public void run() {

                   for (SimpleTalk talk : result) {
                       redisTemplate.opsForZSet().add("hotTalk", talk.getId() + "", talk.getScore());
                       talk.setTalks(talkMapper.queryComments(talk.getId() + ""));

                       objRedisTemplate.opsForHash().put("talk:" + talk.getId(), "talk", talk);
                       objRedisTemplate.opsForHash().put("talk:" + talk.getId(), "vote", talk.getId());


                       List<Integer> voteUserId = talkMapper.queryVoteUser(talk.getId());
                       for (int id : voteUserId) {
                           redisTemplate.opsForSet().add("vote:" + talk.getId(), "user:" + id);
                       }
                       redisTemplate.expire("talk:" + talk.getId(), 2 * TALK_SCHE, TimeUnit.MINUTES);
                       redisTemplate.expire("vote:" + talk.getId(), 2 * TALK_SCHE, TimeUnit.MINUTES);
                   }
               }
           }, 0, TALK_SCHE, TimeUnit.MINUTES);
       }
 }
